import React, { useState } from 'react'
import { useSearch } from '../../hooks/useSearch'
import { Button, IndexBar, List, SearchBar, Space } from 'antd-mobile'
import utils from '../../utils/utils'
import { useNavigate } from 'react-router-dom'
import {throttle} from 'lodash'
const City = () => {
  const { data = { cityList: [], hotCities: [] } } = useSearch('/city', 'get')
  const [searchList,setSearchList]=useState([])
  const [isSearch, setIsSearch] = useState(false);
  const navigate =useNavigate()
  const onSearch = throttle(async(value) => {
    setIsSearch(true);

    const resp = await utils.get('/city/search',{params: {wd: value} })
    console.log(resp.data.data);
    setSearchList(resp.data.data)
  },400)

  const handleClickCity = city =>{
   navigate(-1)
   localStorage.setItem('city',city)
  }
  return (
    <div style={{ height: "100vh", overflow: "hidden" }}>
      <SearchBar placeholder="请输入城市" onSearch={onSearch} 
      onClear={() => {
        setIsSearch(false)
      }}
      ></SearchBar>
      {
        isSearch ? (
          <div>
          {
            searchList.map((v,i)=>{
              return <List.Item key={i} onClick={() => handleClickCity(v.name)}>{v.name}</List.Item>
            })
          }
            
          </div> 
          ): (
          <>
          <Space wrap style={{ padding: 20 }}>
            {
              data.hotCities.map((v, i) => {
                return <Button key={i} onClick={() => handleClickCity(v.name)}>{v.name}</Button>
              })
            }
          </Space>
          <IndexBar>
            {
              data.cityList.map((v, i) => {
                return <IndexBar.Panel key={i} title={v.title} index={v.title}>
                  <List>
                    {
                      v.citys.map((v, i) => {
                        return <List.Item key={i} onClick={() => handleClickCity(v.name)}>{v.name}</List.Item>
                      })
                    }
                  </List>
                </IndexBar.Panel>
              })
            }
          </IndexBar>
        </>
        )}
    </div>
  )
}

export default City
